package org.jasig.cas.authentication;

import com.alibaba.druid.pool.DruidDataSource;
import org.jasig.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler;
import org.jasig.cas.authentication.principal.DefaultPrincipalFactory;
import org.jasig.cas.authentication.principal.PrincipalFactory;
import org.jasig.cas.cuscon.AccountPasswordException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.binding.message.MessageContext;

import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginException;
import javax.validation.constraints.NotNull;
import java.security.GeneralSecurityException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 自定义JDBC认证
 * Created by Administrator on 2017/5/23/023.
 */
public class MyUsersAuthenticationHandler extends AbstractUsernamePasswordAuthenticationHandler {

    private DruidDataSource dataSource;

    @Override
    protected HandlerResult authenticateUsernamePasswordInternal(UsernamePasswordCredential transformedCredential) throws GeneralSecurityException, PreventedException {

        String username = transformedCredential.getUsername();
        String password = transformedCredential.getPassword();

        String SQL = "SELECT id,username,password,createDate from user where username=? AND password=? LIMIT 0,1";
        Connection connection = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
             connection = getDataSource().getConnection();
             stmt = connection.prepareStatement(SQL);
             stmt.setString(1, username);
             stmt.setString(2, password);
             rs = stmt.executeQuery();
            if(rs.next()){
                return createHandlerResult(transformedCredential, this.principalFactory.createPrincipal(username), null);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                if(connection!=null){
                    connection.close();
                }
                if(stmt!=null){
                    stmt.close();
                }
                if(rs!=null){
                    rs.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        throw new FailedLoginException();
    }


    public void setDataSource(DruidDataSource dataSource) {
        this.dataSource = dataSource;
    }

    public DruidDataSource getDataSource() {
        return dataSource;
    }


}
